<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item>
              <el-input
                v-model="listQuery.keyword"
                placeholder="会员名称、缴费金额"
                clearable
                @keyup.enter.native="search()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="listQuery.paymentMethod" placeholder="请选择缴费方式">
                <el-option
                  v-for="(item, index) in paymentMethodList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                v-model="pickerVal"
                type="daterange"
                start-placeholder="缴费开始日期"
                end-placeholder="缴费结束日期"
                :picker-options="pickerOptions"
                value-format="timestamp"
                clearable
                :editable="false"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">
                {{ $t("common.search") }}</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >{{ $t("common.reset") }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <topOpts isJudgePer @add="addEditTemplate()">
            <el-button v-has="'btn_download'" type="text" icon="el-icon-download" @click="exportForm"
              >导出</el-button
            >
            <el-button v-has="'btn_upload'" type="text" icon="el-icon-upload2" @click="uploadForm"
              >导入</el-button
            >
          </topOpts>
          <div class="JNPF-common-head-right">
            <el-tooltip
              effect="dark"
              :content="$t('common.refresh')"
              placement="top"
            >
              <el-link
                icon="icon-ym icon-ym-Refresh JNPF-common-head-icon"
                :underline="false"
                @click="initData()"
              />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table v-loading="listLoading" :data="list" :customColumn="true">
          <el-table-column
            prop="enCode"
            label="订单编号"
            show-overflow-tooltip
            min-width="160"
          />
          <el-table-column
            prop="vipInfoName"
            label="会员名称"
            min-width="160"
          />
          <el-table-column prop="flowState" label="审核状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.flowState == 1">待审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.flowState == 2"
                >已通过</el-tag
              >
              <el-tag type="danger" v-else-if="scope.row.flowState == 3"
                >已驳回</el-tag
              >
              <el-tag type="info" v-else-if="scope.row.flowState == 4"
                >已撤回</el-tag
              >
              <el-tag type="info" v-else-if="scope.row.flowState == 5"
                >已终止</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="缴费金额" width="120">
            <template slot-scope="scope">
              <span>{{ retainNumber(scope.row.amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="expireTime" label="到期时间（续费后）" width="160">
            <template slot-scope="scope">
              <span>{{ jnpf.dateFormat(scope.row.expireTime, 'YYYY-MM-DD')}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="缴费方式" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.paymentMethod == '1' ? '会员支付' : '协会新增' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="payType" label="支付方式" width="100">
            <template slot-scope="scope">
              <span>{{ mateMode(scope.row.payType) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="paymentDate"
            label="缴费时间"
            :formatter="jnpf.tableDateFormat"
            min-width="160"
          />
          <el-table-column prop="approveUserId" label="审核人" width="100" />
          <el-table-column
            prop="approveTime"
            label="审核时间"
            :formatter="jnpf.tableDateFormat"
            width="160"
          />
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <tableOpts
                isJudgePer
                @edit="addEditTemplate(scope.row.id, scope.row.flowState, scope.row)"
                editText="查看"
                :hasDel="false"
              />
            </template>
          </el-table-column>
        </JNPF-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
        <FormCommon v-if="formCommonVisible" ref="FormCommon" @close="closeFormCommon" />
        <Form v-if="formVisible" ref="Form" @close="closeForm" />
        <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />
        <ExportForm v-if="exportFormVisible" ref="exportForm" />
        <ImportForm
          v-if="importFormVisible"
          ref="importForm"
          @refresh="reset()"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { vipAmountList } from "@/api/asso/vip/vipAmount";
import { getVipGrade } from "@/api/asso/vip/vipLevel";
import Form from "./Form";
import FormCommon from "./FormCommon";
import ImportForm from "./ImportForm";
import ExportForm from "./ExportForm";
import columnList from "./columnList";
import FlowBox from "@/views/workFlow/components/FlowBox";
export default {
  name: "asso-vip-vipAmount",
  components: { Form, ImportForm, ExportForm, FlowBox, FormCommon },
  data() {
    return {
      list: [],
      total: 0,
      columnList,
      mergeList: [],
      listLoading: true,
      importFormVisible: false,
      exportFormVisible: false,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        paymentMethod: "",
        startTime: "",
        endTime: "",
        keyword: "",
      },
      formVisible: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const start = new Date();
              const end = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const start = new Date();
              const end = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const start = new Date();
              const end = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      pickerVal: [],
      payModeList: [],
      multipleSelection: [],
      flowVisible: false,
      formCommonVisible: false,
      paymentMethodList: [
        {
          name: '会员支付',
          id: '1'
        },
        {
          name: '协会新增',
          id: '2'
        },
      ]
    };
  },
  created() {
    this.initData();
    this.getPayType();
    this.getColumnList();
    if (!!this.$route.query.type) {
      if (this.$route.query.type == "add") {
        // 会员列表跳入
        this.addEditTemplate(undefined);
        this.$router.push({ query: {} }); //清除路由参数
      }
    }
  },
  methods: {
    initData() {
      this.listLoading = false;
      vipAmountList(this.listQuery)
        .then((res) => {
          this.list = res.data.list;
          this.total = res.data.pagination.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    /**
     * 新增/修改 打开弹窗
     * @param {*} id  审核id
     */
    addEditTemplate(id, flowState, row) {
      if(row && row.payType == 'DGZZ' && row.paymentMethod == '1'){
        let data = {
          id: id || "",
          enCode: "HFGL",
          flowId: "367277626735199301",
          formType: 1,
          opType: flowState ? 0 : "-1",
          status: flowState,
        };
        this.flowVisible = true;
        this.$nextTick(() => {
          this.$refs.FlowBox.init(data);
        });
      }else{
        this.formCommonVisible = true;
        this.$nextTick(() => {
          this.$refs.FormCommon.init(id);
        });
      }
    },
    closeForm(isRefresh) {
      this.formVisible = false;
      if (isRefresh) this.initData();
    },
    closeFormCommon(isRefresh){
      this.formCommonVisible = false;
      if (isRefresh) this.initData();
    },
    // 导入
    uploadForm() {
      this.importFormVisible = true;
      this.$nextTick(() => {
        this.$refs.importForm.init();
      });
    },
    // 导出
    exportForm() {
      this.exportFormVisible = true;
      this.$nextTick(() => {
        this.$refs.exportForm.init(this.listQuery);
      });
    },
    // 查询
    search() {
      if (this.pickerVal && this.pickerVal.length) {
        this.listQuery.startTime = this.pickerVal[0];
        this.listQuery.endTime = this.pickerVal[1];
      } else {
        this.listQuery.startTime = "";
        this.listQuery.endTime = "";
      }
      this.listQuery.currentPage = 1;
      this.listQuery.pageSize = 20;
      this.initData();
    },
    // 重置
    reset() {
      this.pickerVal = [];
      this.listQuery.keyword = "";
      this.listQuery.paymentMethod = "";
      this.search();
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    handleSelectionChange(val) {
      const res = val.map((item) => item.id);
      this.multipleSelection = res;
    },
    // 获取会员缴费方式
    getPayType() {
      getVipGrade("367299187424887877").then((res) => {
        if (res.code == 200) {
          this.payModeList = res.data.list;
        }
      });
    },
    mateMode(type) {
      let str = "";
      this.payModeList.forEach((item) => {
        if (type == item.enCode) {
          str = item.fullName;
        }
      });
      return str;
    },
    getColumnList() {
      // 没有开启权限
      this.columnOptions = this.transformColumnList(this.columnList);
    },
    transformColumnList(columnList) {
      let list = [];
      for (let i = 0; i < columnList.length; i++) {
        const e = columnList[i];
        if (!e.prop.includes("-")) {
          list.push(e);
        } else {
          let prop = e.prop.split("-")[0];
          let label = e.label.split("-")[0];
          let vModel = e.prop.split("-")[1];
          let newItem = {
            align: "center",
            jnpfKey: "table",
            prop,
            label,
            children: [],
          };
          e.vModel = vModel;
          if (!this.expandObj.hasOwnProperty(`${prop}Expand`))
            this.$set(this.expandObj, `${prop}Expand`, false);
          if (!list.some((o) => o.prop === prop)) list.push(newItem);
          for (let i = 0; i < list.length; i++) {
            if (list[i].prop === prop) {
              list[i].children.push(e);
              break;
            }
          }
        }
      }
      this.getMergeList(list);
      this.getExportList(list);
      return list;
    },
    getMergeList(list) {
      let newList = JSON.parse(JSON.stringify(list));
      newList.forEach((item) => {
        if (item.children && item.children.length) {
          let child = {
            prop: item.prop + "-child-first",
          };
          item.children.unshift(child);
        }
      });
      newList.forEach((item) => {
        if (item.children && item.children.length > 0) {
          item.children.forEach((child, index) => {
            if (index == 0) {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 1,
                colspan: item.children.length,
              });
            } else {
              this.mergeList.push({
                prop: child.prop,
                rowspan: 0,
                colspan: 0,
              });
            }
          });
        } else {
          this.mergeList.push({
            prop: item.prop,
            rowspan: 1,
            colspan: 1,
          });
        }
      });
    },
    getExportList(list) {
      let exportList = [];
      for (let i = 0; i < list.length; i++) {
        if (list[i].jnpfKey === "table") {
          for (let j = 0; j < list[i].children.length; j++) {
            exportList.push(list[i].children[j]);
          }
        } else {
          exportList.push(list[i]);
        }
      }
      this.exportList = exportList;
    },
    colseFlow(isrRefresh) {
      this.flowVisible = false;
      if (isrRefresh) this.reset();
    },
    // 保留两位小数
    retainNumber(val){
      return Number(val).toFixed(2)
    }
  },
};
</script>